import datetime
import logging

from absl import app

from coin.base.datetime_util import to_datetime
from coin.exchange.okex.kr_rest.product import OkexProduct
import experimental.prophet as prophet


def model():
  ts = prophet.global_timestamp()
  timer_1s = prophet.timer('1s')

  product = OkexProduct.FromStr('BTC-USDT')
  feed = prophet.fastfeed_coin(product, 'Spot.Okex.v3')
  trade = prophet.trade(feed)

  tq = prophet.time_moving_window(trade.qty, '1s').sum().named_ref('trade_qty')
  tv = prophet.time_moving_window(trade.qty * trade.price, '1s').sum().named_ref('trade_volume')
  vwap = (tv / tq).named_ref('vwap')

  with prophet.control_if(ts % 10**9 == 0):
    # prophet.printer('%t vwap=%s volume=%s qty=%s', ts, vwap, tv, tq)
    aggregator = prophet.scalar_value_aggregator([ts, tq, tv, vwap])

  return aggregator


def eval_callback(graph):
  ts = graph.get_named_variable('global_timestamp').value
  tq = graph.get_named_variable('trade_qty').value
  tv = graph.get_named_variable('trade_volume').value
  vwap = graph.get_named_variable('vwap').value

  if ts % 10**9 == 0:
    if tq is not None:
      print('Eval callback: %s vwap=%-8.2f volume=%-10.2f qty=%.2f' %
            (to_datetime(ts), vwap, tv, tq))


def main(argv):
  df = prophet.run_from_fastfeed_multiprocess(model,
                                              datetime.date(2019, 8, 1),
                                              datetime.datetime(2019, 8, 1, 2),
                                              machine='feed-01.ap-northeast-1.aws',
                                              eval_callback=eval_callback,
                                              use_run_cache=False)

  print(df)


if __name__ == '__main__':
  logging.basicConfig(level='DEBUG')
  app.run(main)
